package uni.UNIBEE7B8D.CommonTool;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.appcompat.widget.AppCompatEditText;

import java.util.ArrayList;
import java.util.List;

import uni.UNIBEE7B8D.R;

public class LeftTextEditText  extends AppCompatEditText/* implements TextWatcher */ {
    private Context context;
    /**
     * 左侧文字
     */
    private String       leftText              = "";
    /**
     * 右侧文字
     */
    private String       rightText             = "";
    /**
     * 左侧文字的大小
     */
    private float        LeftTextSize          = -1;
    /**
     * 右侧文字的大小
     */
    private float        rightTextSize         = -1;
    /**
     * 左侧文字的颜色
     */
    private int          leftTextColor;
    /**
     * 右侧文字的颜色
     */
    private int          rightTextColor;
    /**
     * 左侧文字的字体
     */
    private int          leftTextFont;
    /**
     * 右侧文字的字体
     */
    private int          rightTextFont;
    /**
     * 底部线的默认颜色
     */
    private int          downLineDefaultColor;
    /**
     * 底部线获取焦点颜色
     */
    private int          downLineFocusColor;
    /**
     * 左侧文字的画笔
     */
    private Paint leftPaint;
    /**
     * 右侧文字的画笔
     */
    private Paint        rightPaint;
    /**
     * 输入文字的画笔
     */
    private TextPaint paint;
    /**
     * 底部线的画笔
     */
    private Paint        downLinePaint;
    /**
     * 光标距左侧文字的距离
     */
    private float        leftTextPadding;
    /**
     * 光标距右侧文字的距离
     */
    private float        rightTextPadding;
    /**
     * 存放字体路径
     */
    private List<String> pathList;
    /**
     * 点击的是否是左侧文字
     */
    private Boolean      isSelectLeftText      = false;
    /**
     * 点击的是否是右侧图片
     */
    private Boolean      isSelectRightDrawIcon = false;

    public LeftTextEditText(Context context) {
        this(context, null);
    }

    public LeftTextEditText(Context context, AttributeSet attrs) {
        this(context, attrs, R.attr.editTextStyle);
        this.context = context;
    }

    public LeftTextEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        init(context, attrs, defStyleAttr);
    }

    private void init(Context context, AttributeSet attrs, int defStyleAttr) {
        paint = getPaint();
        pathList = new ArrayList<>();//默认添加的几个字体样式
        pathList.add(0, "fonts/source_han_sans_cn_regular.otf");
        pathList.add(1, "fonts/source_han_sans_cn_medium.otf");
        pathList.add(2, "fonts/roboto_medium.ttf");
        pathList.add(3, "fonts/din_medium.otf");
        //这部分代码时控件在布局文件中设置属性的代码
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.LeftTextEditText, defStyleAttr, 0);
        leftText = typedArray.getString(R.styleable.LeftTextEditText_leftText);
        rightText = typedArray.getString(R.styleable.LeftTextEditText_rightText);
        leftTextColor = typedArray.getColor(R.styleable.LeftTextEditText_leftTextColor, getResources().getColor(R.color.blank));
        rightTextColor = typedArray.getColor(R.styleable.LeftTextEditText_rightTextColor, getResources().getColor(R.color.blank));
        LeftTextSize = typedArray.getDimension(R.styleable.LeftTextEditText_leftTextSize, sp2px(16f));
        rightTextSize = typedArray.getDimension(R.styleable.LeftTextEditText_rightTextSize, sp2px(14f));
        leftTextPadding = typedArray.getDimension(R.styleable.LeftTextEditText_leftTextPadding, dp2px(26));
        rightTextPadding = typedArray.getDimension(R.styleable.LeftTextEditText_rightTextPadding, dp2px(8));
        leftTextFont = typedArray.getInteger(R.styleable.LeftTextEditText_leftTextFont, 0);
        rightTextFont = typedArray.getInteger(R.styleable.LeftTextEditText_rightTextFont, 2);
        downLineDefaultColor = typedArray.getColor(R.styleable.LeftTextEditText_downLineDefaultColor, getResources().getColor(R.color.blank));
        downLineFocusColor = typedArray.getColor(R.styleable.LeftTextEditText_downLineDefaultColor, getResources().getColor(R.color.blank));
        typedArray.recycle();
        setBackground(null);
        initPaint();
    }

    private void initPaint() {
        leftPaint = new Paint();
        leftPaint.setColor(leftTextColor);
        leftPaint.setTextSize(LeftTextSize);
       // setTextFont(leftPaint, leftTextFont);
        leftPaint.setAntiAlias(true);

        downLinePaint = new Paint();
        downLinePaint.setColor(downLineDefaultColor);
        downLinePaint.setStrokeWidth(dp2px(1));
        downLinePaint.setAntiAlias(true);

        rightPaint = new Paint();
        rightPaint.setColor(rightTextColor);
        rightPaint.setTextSize(rightTextSize);
        //setTextFont(rightPaint, rightTextFont);
        rightPaint.setAntiAlias(true);

        // 若果设置左边文字，需要重新计算Padding
        if (!TextUtils.isEmpty(leftText)) {
            int leftPadding = (int) (leftPaint.measureText(leftText) + getPaddingLeft() + leftTextPadding);
            //设置光标距离左侧的距离
            setPadding(leftPadding, getPaddingTop(), getPaddingRight(), getPaddingBottom());
        }
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
        // 控件获取焦点时改变底部线的颜色
        downLinePaint.setColor(focused ? downLineFocusColor : downLineDefaultColor);
        invalidate();//更新视图
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //        float baseLineY =(getMeasuredHeight() - leftPaint.getTextSize()) / 2 + leftPaint.getTextSize();
        // 绘制左侧文字，使用getBaseline()，获取输入内容的文本基线，让所有文本对齐
        if (!TextUtils.isEmpty(leftText)) {
            canvas.drawText(leftText, getScaleX(), getBaseline(), leftPaint);
        }
        // 绘制右侧文字，使用getBaseline()，获取输入内容的文本基线，让所有文本对齐
        float width = paint.measureText(getText().toString());
        if (!TextUtils.isEmpty(rightText)) {
            if (width == 0) {
                /*(getMeasuredHeight() - rightPaint.getTextSize()) / 2 + rightPaint.getTextSize()*/
                canvas.drawText(rightText, (getPaddingLeft() + width), getBaseline(), rightPaint);
            } else {
                /*(getMeasuredHeight() - rightPaint.getTextSize()) / 2 + rightPaint.getTextSize()*/
                canvas.drawText(rightText, (getPaddingLeft() + width + rightTextPadding), getBaseline(), rightPaint);
            }
        }
        // 绘制底部的线
        canvas.drawLine(getScrollX(), this.getHeight() - dp2px(1), getScrollX() + this.getWidth(), this.getHeight() - dp2px(1), downLinePaint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (getCompoundDrawables()[2] != null) {
                // 0 ：drawableLeft左侧图标。1：drawableTop。2：drawableRight.3:drawableButton
                int eventX = (int) event.getX();//触摸点左上角x坐标,相对于控件本身的坐标
                int eventY = (int) event.getY();//触摸点左上角Y坐标,相对于控件本身的坐标
                Rect rect = getCompoundDrawables()[2].getBounds();// 返回图片的边框界线
                int height = rect.height();
                int distance = (getHeight() - height) / 2;// 获取图片顶部边缘到控件顶部边缘的距离  getHeight()获取控件的高度
                // getWidth() 获取控件的宽度。getTotalPaddingRight()，获取图片左边缘到控件右边缘的距离。 getPaddingRight()获取图片右边缘到控件右边缘的距离
                Boolean isInnerWidth = eventX > (getWidth() - getTotalPaddingRight()) && eventX < (getWidth() - getPaddingRight());
                Boolean isInnerHeight = eventY > distance && eventY < (distance + height);
                if (isInnerHeight && isInnerWidth) {
                    // 触摸在图片上
                    isSelectRightDrawIcon = true;
                    if (onRightDrawIconListener != null) {
                        onRightDrawIconListener.onClick();
                    }
                    invalidate();
                    return false;
                } else {
                    isSelectRightDrawIcon = false;
                }
            }

            if (leftText != null) {
                int eventX = (int) event.getX();//触摸点左上角x坐标,相对于控件本身的坐标
                int eventY = (int) event.getY();//触摸点左上角Y坐标,相对于控件本身的坐标
                int viewX = 0;//当前控件左上角x坐标,相对于控件本身的坐标
                int viewY = 0;//当前控件左上角y坐标,相对于控件本身的坐标
                int leftTextWidth = (int) leftPaint.measureText(leftText);// 文字的宽度
                boolean isEventWidth = eventX < (viewX + leftTextWidth) && eventX > viewX;
                boolean isEventHeight = eventY < (viewY + getHeight()) && eventY > viewY;// getHeight()获取控件的高度
                if (isEventHeight && isEventWidth) {
                    //触摸在左侧文字上
                    isSelectLeftText = true;
                    if (onLeftTextListener != null) {
                        onLeftTextListener.onClick();
                    }
                    invalidate();
                    return false;
                } else {
                    isSelectLeftText = false;
                }
            }
        }
        return super.onTouchEvent(event);
    }

    //    @Override
    //    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    //
    //    }
    //
    //    @Override
    //    public void onTextChanged(CharSequence s, int start, int before, int count) {
    //
    //    }
    //
    //    @Override
    //    public void afterTextChanged(Editable s) {
    //        int drawIconLen = 0;
    //        if (getCompoundDrawables()[2] != null) {
    //            drawIconLen = getTotalPaddingRight();
    //        } else {
    //            drawIconLen = 0;
    //        }
    //        float length;// 可用长度
    //        float leftWidth = leftPaint.measureText(leftText);
    //        float rightWidth = rightPaint.measureText(rightText);
    //        float textWidth = getPaint().measureText(getText().toString().trim());
    //        if (rightText != null) {
    //            length = getWidth() - leftWidth - leftTextPadding - rightWidth - rightTextPadding - textWidth - drawIconLen;
    //        } else {
    //            length = getWidth() - leftWidth - leftTextPadding - rightWidth - textWidth - drawIconLen;
    //        }
    //        if (!(length > 0)) {
    //            int len = s.toString().length();
    //            s.delete(len - 2, len - 1);
    //        }
    //
    //    }

    //定义一个接口
    public interface OnRightDrawIconListener {
        public void onClick();
    }

    //定义一个接口
    public interface OnLeftTextListener {
        public void onClick();
    }

    //定义一个接口对象listener
    private OnRightDrawIconListener onRightDrawIconListener;
    //定义一个接口对象listener
    private OnLeftTextListener      onLeftTextListener;

    //获得接口对象的方法。
    public void setOnRightDrawIconListener(OnRightDrawIconListener onRightDrawIconListener) {
        this.onRightDrawIconListener = onRightDrawIconListener;
    }

    //获得接口对象的方法。
    public void setOnLeftTextListener(OnLeftTextListener onLeftTextListener) {
        this.onLeftTextListener = onLeftTextListener;
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        super.setText(text, type);
        if (!TextUtils.isEmpty(text)) {
            setSelection(text.toString().length() - 1);
        }
    }

    private int sp2px(float spValue) {
        float spDensity = getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * spDensity + 0.5f);
    }

    private int dp2px(double dip) {
        float dpDensity = getContext().getResources().getDisplayMetrics().density;
        return (int) (dip * dpDensity + 0.5);
    }

    /**
     * 设置字体
     *
     * @param paint 画笔
     * @param index 字体的索引
     */
    private void setTextFont(Paint paint, int index) {
        String path = pathList.get(index);
        Typeface typeface = Typeface.createFromAsset(getContext().getAssets(), path);
        paint.setTypeface(typeface);
        this.setIncludeFontPadding(false);//去除文字字体边距
    }

    /**
     * 获取右侧文字（单位）
     */
    public String getRightText() {
        return rightText;
    }

    /**
     * 获取左侧文字（固定值）
     */
    public String getLeftText() {
        return leftText;
    }

    /**
     * 设置左侧文字（固定值）
     */
    public void setLeftText(String leftText) {
        this.leftText = leftText;
    }

    /**
     * 设置右侧文字（单位）
     */
    public void setRightText(String rightText) {
        this.rightText = rightText;
    }

    /**
     * 是否点击在左侧文字上
     *
     * @return
     */
    public Boolean getIsSelectLeftText() {
        return isSelectLeftText;
    }

    /**
     * 是否点击在右侧图片上
     */
    public Boolean getIsSelectRightDrawIcon() {
        return isSelectRightDrawIcon;
    }
}

